/*

Input: newdata/estimation_prep_ltw18 [prepared precinct-level panel]

Output:
	- Figure 10, D.13
	- Table E.6
	- Table E.7
	
Tasks: 	
	* Triple Diff estimator: Heterogeneity by Precinct Characteristic
	* Robustness: DDD conditional on log walking distance
	* Correlation matrix of heterog. dimensions (2013)
	* Export figure and table
	

*/	
	
* PULL: Precinct-level data
	use "$newdata/estimation_prep_ltw18.dta", clear
	
********************************************************************************
 //	 Prep Estimation //
********************************************************************************
	
	// clone variable b/c varname is too long for outreg below
	clonevar mpreis_rent=mpreis_flats_rent
	
	// relabel variable for Figure header
	lab var turnout_urne 	  "Polling place turnout"
		
	// Standardize variables as of 2013 (mean zero, unit SD), gen: z_*
	foreach v of varlist $ctr wb_60plus mpreis_rent {
		zscore `v' if wahl_id==1						// LTW13
		bys sb_new (wahl_id): replace z_`v'=z_`v'[1]	//time constant as of 2013
		local lb: var lab `v'
		local lb_n=subinstr("`lb'","\%","%",.)

		lab var z_`v' "`lb_n'"
	}
	
	
	// set global containing vars for het analysis
	global het z_wb_60plus z_wb_18t24 z_hh_kids z_mpreis_rent z_ew_dtmihi z_avg_dur	
	
********************************************************************************
 // Corrs + Sumstats among vars used in heterogeneity, 2013, N=618 (Table E7) //
********************************************************************************

* TABLE E7. Summary Statistics and Correlations among Precinct Characteristics, 2013
pwcorr wb_60plus wb_18t24 hh_kids mpreis_rent ew_dtmihi  avg_dur if wahl_id==1, star(.05)
mkcorr wb_60plus wb_18t24 hh_kids mpreis_rent ew_dtmihi  avg_dur if wahl_id==1, mdec(3) cdec(3) ///
	means replace log("${tables}/Table_E7_corrs_het_dimensions_2013") sig

	

********************************************************************************
 // Heterogeneity: DDD by 2013 precinct characteristics //
********************************************************************************		
	
	// Labels for figure
	local j=1
	foreach v of varlist $het {
		local lb: var lab `v'
		local x = "`: word `j' of `c(alpha)''"
		lab var `v' "(`x') `lb'"
		local ++j
	}
	
estimates clear
outreg, clear
foreach h of varlist $het  {
	
	// gen leads and lags
	cap drop L* F*
	forvalues l = 7(-1)1 {
		gen F`l'event = K==-`l'
		gen F`l'event_n = F`l'event * `h'
		lab var F`l'event_n "\hspace{.7cm}Reassignment (#t-`l'#)"		
	}	
	forvalues l = 0/7 {
		gen L`l'event = K==`l'
		gen L`l'event_n = L`l'event * `h'
		lab var L`l'event_n "\hspace{.7cm}Reassignment (#t+`l'#)"
	}
	order *event_n, last
	order F1event*, last
	
	// Estimate ES: base levels + interactions
	foreach v in urne pos_req tot_req{
	
		 reghdfe turnout_`v' F7event-L7event F7event_n-L7event_n F1event F1event_n $ctr $wgt if smpl_trim ==1, absorb(i.wahl_id#i.stadtbez i.sb_new) cluster(sb_new)
		estimates store `h'_`v'
	 	qui outreg,  $opt  keep(F4event_n-L2event_n) store(`v'_`h') ctitle("","`:var lab `h''")
	}
	
		// PLOT: All 3 outcomes in one plot
		event_plot  `h'_urne `h'_pos_req `h'_tot_req , ///
		stub_lag(L#event_n ) stub_lead(F#event_n ) plottype(scatter) ciplottype(rcap) ///
		together perturb(-0.23(0.23)0.23) trimlead(4) trimlag(2) noautolegend ///
		graph_opt(xtitle("") ytitle("Voter turnout in %""(estimates)", size(small)) xlabel(-4(1)2) xtitle("Election since reassignment", size(small)) ///
			legend(pos(12) order(1 "Polling place turnout" 3 "Mail-in turnout" 5 "Total turnout" ) size(vsmall) col(1) region(style(none)) title("{bf:Outcomes:}", pos(11) just(left) span bexpand size(vsmall))) ///
			xline(-0.5, lcolor(black) lpattern(solid)) yline(0, lcolor(gray) lpat(solid)) ylabel(, angle(horizontal)) ///
			title("`:var lab `h''", size(small)) ///
			name(`h', replace) ) ///
		lag_opt1(msymbol(S) msize(2.5pt) color(navy)) 		lag_ci_opt1(color(navy)) ///
		lag_opt2(msymbol(O) msize(2.5pt) color(maroon)) 	lag_ci_opt2(color(maroon)) ///  
		lag_opt3(msymbol(Oh) msize(2.5pt) color(black)) 	lag_ci_opt3(color(black))		
		
		
		// PLOT: 2 outcomes (mail, pp)
		event_plot  `h'_urne `h'_pos_req /*`h'_tot_req*/ , ///
		stub_lag(L#event_n ) stub_lead(F#event_n ) plottype(connect) ciplottype(rcap) ///
		together perturb(-0.1(0.2)0.1) trimlead(4) trimlag(2) noautolegend ///
		graph_opt(ytitle("Voter turnout in %""(estimates)", size(small)) xlabel(-4(1)2) xtitle("Election since reassignment", size(medsmall)) ///
		legend(pos(12) order(1 "Polling place turnout" 3 "Mail-in turnout") row(1) region(style(none))) ///
			xline(-0.5, lcolor(black) lpattern(solid)) yline(0, lcolor(gray) lpat(solid)) ylabel(, angle(horizontal)) ///
			name(`h'_urne_pos, replace) ) ///
		lag_opt1(msymbol(S) msize(2.5pt) color(navy)) 	lag_ci_opt1(color(navy)) ///
		lag_opt2(msymbol(O) msize(2.5pt) color(maroon)) lag_ci_opt2(color(maroon)) 

		// PLOT: 1 outcome (overall)
		event_plot  `h'_tot_req, ///
		stub_lag(L#event_n ) stub_lead(F#event_n ) plottype(connect) ciplottype(rcap) ///
		together trimlead(4) trimlag(2)  noautolegend ///
		graph_opt(ytitle("Voter turnout in %""(estimates)", size(small)) xlabel(-4(1)2) xtitle("Election since reassignment", size(medsmall)) ///
			legend(pos(11) order(1 "Total turnout") row(1) region(style(none))) ///
			xline(-0.5, lcolor(black) lpattern(solid)) yline(0, lcolor(gray) lpat(solid)) ylabel(, angle(horizontal)) ///
			name(`h'_tot_req,replace) ) ///
		lag_opt1(msymbol(Oh) msize(2.5pt) color(black)) lag_ci_opt1(color(black)) 
}
	
	* PLOT: FIGURE 10. Effect Heterogeneity by Precinct Characteristics (Triple Difference Estimates)
	grc1leg z_wb_60plus_urne_pos 		z_wb_60plus_tot_req z_wb_60plus, leg(z_wb_60plus) pos(12) col(2) imargins(small) xcommon ycommon name(gr_z_wb_60plus, replace) ///
	title("{bf:Panel A.} Heterogeneity by % Electorate Aged 60+" 	,nobox span bexpand justification(left) size(small))
	gr_edit .plotregion1.graph3.draw_view.setstyle, style(no) 		// erase extra plot
	grc1leg z_wb_18t24_urne_pos 		z_wb_18t24_tot_req, row(1) imargins(small) xcommon ycommon name(gr_z_wb_18t24, replace) ///
	title("{bf:Panel B.} Heterogeneity by % Electorate Aged 18-24"	,nobox span bexpand justification(left) size(small)) 	
	grc1leg z_hh_kids_urne_pos 		z_hh_kids_tot_req, row(1) 		imargins(small) xcommon ycommon name(gr_z_hh_kids, replace) ///
	title("{bf:Panel C.} Heterogeneity by % Households with Children",nobox span bexpand justification(left) size(small))	
	grc1leg z_mpreis_rent_urne_pos 	z_mpreis_rent_tot_req, row(1) 	imargins(small) xcommon ycommon name(gr_z_mpreis_rent, replace) ///
	title("{bf:Panel D.} Heterogeneity by Average Quoted Rent per sqm",nobox span bexpand justification(left) size(small)) 
	grc1leg z_ew_dtmihi_urne_pos 		z_ew_dtmihi_tot_req, row(1) 	imargins(small) xcommon ycommon name(gr_z_ew_dtmihi, replace) ///
	title("{bf:Panel E.} Heterogeneity by % Germans with Migrant Background",nobox span bexpand justification(left) size(small)) 
	
	grc1leg gr_z_wb_60plus gr_z_wb_18t24 gr_z_hh_kids gr_z_mpreis_rent gr_z_ew_dtmihi , col(1) pos(12) imargins(zero)
	gr_edit .legend.Edit , style(rows(1)) style(cols(0)) keepstyles // legend
	gr_edit .legend.title.DragBy -3.1 -12.6	
	gr_edit .style.editstyle declared_ysize(8.4) editcopy			// size	
	graph export "$figures/Figure_10_ES_het_z_charac_top5.pdf", replace		
			
	
		// Test if overall effects are different from zero: % Electorate aged 60+
		estimates restore z_wb_60plus_tot_req
		lincom (L0event+L0event_n + L1event+L1event_n+L2event+L2event_n)
		test (L0event+L0event_n + L1event+L1event_n+L2event+L2event_n)==0
		test (L0event+L0event_n)=0
		test L1event+L1event_n=0
		test L2event+L2event_n=0
		test (L0event+L0event_n)=(L1event+L1event_n)=(L2event+L2event_n)=0 // jointly !=0 in 0,1,2
		test (L1event+L1event_n)=(L2event+L2event_n)=0 // jointly !=0 in 1,2

	* TABLE E6. Heterogeneity by Precinct Characteristics–Triple Difference Estimates
	// EXPORT Table (ONLY triple diff coefs)
		local n : word count $het
		foreach v in urne pos_req tot_req{
			qui outreg, replay(`v'_`:word 1 of $het') store(`v')
			forvalues j=2/`n' {
				qui outreg, replay(`v') merge(`v'_`:word `j' of $het')
			}
		}
		qui outreg, replay(urne) title("&(1)&(2)& (3)&(4)& (5)& (6)"\ "\midrule" \ "\multicolumn{3}{l}{\textbf{Panel A:} Effect on Turnout at the Polling Place}" \"\midrule") ///
			addrow("\midrule" \ "\multicolumn{3}{l}{\textbf{Panel B:} Effect on Turnout via Mail}" \ "\midrule") store(tab)
		qui outreg, replay(tab) append(pos_req) addrow("\midrule" \ "\multicolumn{3}{l}{\textbf{Panel C:} Effect on Total Turnout}" \ "\midrule") store(tab)
		outreg using "$tables/Table_E6_ES_het_z_charac", replay(tab) append(tot_req) fragment tex replace
		cleantex "$tables/Table_E6_ES_het_z_charac.tex" , nodisplay	replace
		
	
		
		

********************************************************************************
 // Robustness: Reestimate DDD, controlling  for log distance (Figure D13) //		
********************************************************************************
	// labels for figure
	local j=1
	foreach v of varlist $het {
		local lb: var lab `v'
		local x = "`: word `j' of `c(alpha)''"
		lab var `v' "(`x') `lb'"
		local ++j
	}
	
estimates clear
outreg, clear
foreach h of varlist $het  {
	
	// gen leads and lags
	cap drop L* F*
	forvalues l = 7(-1)1 {
		gen F`l'event = K==-`l'
		gen F`l'event_n = F`l'event * `h'
		lab var F`l'event_n "\hspace{.7cm}Reassignment (#t-`l'#)"		
	}	
	forvalues l = 0/7 {
		gen L`l'event = K==`l'
		gen L`l'event_n = L`l'event * `h'
		lab var L`l'event_n "\hspace{.7cm}Reassignment (#t+`l'#)"
	}
	order *event_n, last
	order F1event*, last
	

	// Estimate ES: base levels + interactions + CONTROL for log sreet dist
	foreach v in urne pos_req tot_req{
	
		 reghdfe turnout_`v' F7event-L7event F7event_n-L7event_n F1event F1event_n ln_street_dist $ctr $wgt if smpl_trim ==1, absorb(i.wahl_id#i.stadtbez i.sb_new) cluster(sb_new)
		estimates store `h'_`v'
	 	qui outreg,  $opt  keep(F4event_n-L2event_n) store(`v'_`h') ctitle("","`:var lab `h''")	 	
	}
	
		// PLOT: All 3 outcomes in one plot
		event_plot  `h'_urne `h'_pos_req `h'_tot_req , ///
		stub_lag(L#event_n ) stub_lead(F#event_n ) plottype(scatter) ciplottype(rcap) ///
		together perturb(-0.23(0.23)0.23) trimlead(4) trimlag(2) noautolegend ///
		graph_opt(xtitle("") ytitle("Voter turnout in %""(estimates)", size(small)) xlabel(-4(1)2) xtitle("Election since reassignment", size(small)) ///
			legend(pos(12) order(1 "Polling place turnout" 3 "Mail-in turnout" 5 "Total turnout" ) size(vsmall) col(1) region(style(none)) title("{bf:Outcomes:}", pos(11) just(left) span bexpand size(vsmall))) ///
			xline(-0.5, lcolor(black) lpattern(solid)) yline(0, lcolor(gray) lpat(solid)) ylabel(, angle(horizontal)) ///
			title("`:var lab `h''", size(small)) ///
			name(`h', replace) ) ///
		lag_opt1(msymbol(S) msize(2.5pt) color(navy)) 		lag_ci_opt1(color(navy)) ///
		lag_opt2(msymbol(O) msize(2.5pt) color(maroon)) 	lag_ci_opt2(color(maroon)) ///  
		lag_opt3(msymbol(Oh) msize(2.5pt) color(black)) 	lag_ci_opt3(color(black))		
		
		// PLOT: 2 outcomes (mail, pp)
		event_plot  `h'_urne `h'_pos_req /*`h'_tot_req*/ , ///
		stub_lag(L#event_n ) stub_lead(F#event_n ) plottype(connect) ciplottype(rcap) ///
		together perturb(-0.1(0.2)0.1) trimlead(4) trimlag(2) noautolegend ///
		graph_opt(ytitle("Voter turnout in %""(estimates)", size(small)) xlabel(-4(1)2) xtitle("Election since reassignment", size(medsmall)) ///
		legend(pos(12) order(1 "Polling place turnout" 3 "Mail-in turnout") row(1) region(style(none))) ///
			xline(-0.5, lcolor(black) lpattern(solid)) yline(0, lcolor(gray) lpat(solid)) ylabel(, angle(horizontal)) ///
			name(`h'_urne_pos, replace) ) ///
		lag_opt1(msymbol(S) msize(2.5pt) color(navy)) 	lag_ci_opt1(color(navy)) ///
		lag_opt2(msymbol(O) msize(2.5pt) color(maroon)) lag_ci_opt2(color(maroon)) 

		// PLOT: 1 outcome (overall)
		event_plot  `h'_tot_req, ///
		stub_lag(L#event_n ) stub_lead(F#event_n ) plottype(connect) ciplottype(rcap) ///
		together trimlead(4) trimlag(2)  noautolegend ///
		graph_opt(ytitle("Voter turnout in %""(estimates)", size(small)) xlabel(-4(1)2) xtitle("Election since reassignment", size(medsmall)) ///
			legend(pos(11) order(1 "Total turnout") row(1) region(style(none))) ///
			xline(-0.5, lcolor(black) lpattern(solid)) yline(0, lcolor(gray) lpat(solid)) ylabel(, angle(horizontal)) ///
			name(`h'_tot_req,replace) ) ///
		lag_opt1(msymbol(Oh) msize(2.5pt) color(black)) 	lag_ci_opt1(color(black)) 
	
	
}
	
	* PLOT: FIGURE D13. Effect Heterogeneity by Precinct Characteristics Conditional on Distance
	grc1leg z_wb_60plus_urne_pos 		z_wb_60plus_tot_req z_wb_60plus, leg(z_wb_60plus) pos(12) col(2) imargins(small) xcommon ycommon name(gr_z_wb_60plus, replace) ///
	title("{bf:Panel A.} Heterogeneity by % Electorate Aged 60+" 	,nobox span bexpand justification(left) size(small))
	gr_edit .plotregion1.graph3.draw_view.setstyle, style(no) 		// erase extra plot
	grc1leg z_wb_18t24_urne_pos 		z_wb_18t24_tot_req, row(1) imargins(small) xcommon ycommon name(gr_z_wb_18t24, replace) ///
	title("{bf:Panel B.} Heterogeneity by % Electorate Aged 18-24"	,nobox span bexpand justification(left) size(small)) 	
	grc1leg z_hh_kids_urne_pos 		z_hh_kids_tot_req, row(1) 		imargins(small) xcommon ycommon name(gr_z_hh_kids, replace) ///
	title("{bf:Panel C.} Heterogeneity by % Households with Children",nobox span bexpand justification(left) size(small))	
	grc1leg z_mpreis_rent_urne_pos 	z_mpreis_rent_tot_req, row(1) 	imargins(small) xcommon ycommon name(gr_z_mpreis_rent, replace) ///
	title("{bf:Panel D.} Heterogeneity by Average Quoted Rent per sqm",nobox span bexpand justification(left) size(small)) 
	grc1leg z_ew_dtmihi_urne_pos 		z_ew_dtmihi_tot_req, row(1) 	imargins(small) xcommon ycommon name(gr_z_ew_dtmihi, replace) ///
	title("{bf:Panel E.} Heterogeneity by % Germans with Migrant Background",nobox span bexpand justification(left) size(small)) 
	
	grc1leg gr_z_wb_60plus gr_z_wb_18t24 gr_z_hh_kids gr_z_mpreis_rent gr_z_ew_dtmihi , col(1) pos(12) imargins(zero)
	gr_edit .legend.Edit , style(rows(1)) style(cols(0)) keepstyles 
	gr_edit .legend.title.DragBy -3.1 -12.6	
	gr_edit .style.editstyle declared_ysize(8.4) editcopy			
	graph export "$figures/Figure_D13_ES_het_z_charac_top5_ln_dist.pdf", replace		
			
